// ==UserScript==
// @name         aliexpress ask list
// @namespace    hth
// @version      0.7
// @description  get aliexpress ask
// @author       hth
// @updateURL    https://gitee.com/hthgit/tampermonkey/raw/master/lib/aliexpress_ask_buyers.user.js
// @match        *://www.aliexpress.com/item/*
// @require      https://code.jquery.com/jquery-3.6.0.min.js
// @grant GM_setClipboard
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// ==/UserScript==

(function() {
    'use strict';

    function request(opts) {
        return Promise.resolve($.ajax(opts));
    }

    function getQuestion(productId){
        return request({
            "type": "GET",
            "url": `https://www.aliexpress.com/aeglodetailweb/api/questions?productId=${productId}&currentPage=1&pageSize=5`
        });
    }

    function getAnswer(productId, serialNumber){
        return request({
            "type": "GET",
            "url": `https://www.aliexpress.com/aeglodetailweb/api/questions/answers?productId=${productId}&serialNumber=${serialNumber}&currentPage=1&pageSize=6`,
        });
    }

    function getContent(info) {
        return info.translateContent || info.content;
    }

    GM_registerMenuCommand("复制问答", () => {
        let productId = runParams.data.commonModule.productId;
        getQuestion(productId).then(res => {
            Promise.all( res.body.questionList.map(q => getAnswer(productId, q.serialNumber)) ).then(rtList => {
                let allConten = rtList.map(rt => {
                    let q = rt.body.questionResult;
                    return `【${getContent(q)}】\n\n${q.answers.map(a => getContent(a)).join('\n\n')}`;
                }).join('\n\n\n');
                console.log(allConten);
                GM_setClipboard(allConten);
                alert('复制成功！');
            });
        });
    });
})();